<!DOCTYPE html>
<html lang="en">
    <head>
        <meta charset="UTF-8" />
        <meta name="viewport" content="width=device-width, initial-scale=1.0" />
        <title>Debounce Demo</title>
        <style>
            body {
                height: 300vh;
            }
        </style>
    </head>
    <body>
        <input type="text" />
        <script>
            function mousemove(e) {
                console.log('鼠标移动了');
            }

            function changeInput(e) {
                console.log('changeInput', this);
                console.log(e.target.value);
            }

            function onScroll() {
                console.log('滚动条动了');
            }

            // document
            //     .querySelector('input')
            //     .addEventListener('input', debounce(changeInput), false);

            // document.addEventListener('mousemove', debounce(mousemove), false);

            // document.addEventListener('scroll', onScroll, false);

            // 防抖函数
            function debounce(fn, delay = 500, isStart = true) {
                let timer;
                let isFirst = true;
                return function (...args) {
                    let _this = this;
                    if (isFirst && isStart) {
                        fn.apply(_this, args);
                        isFirst = false;
                    }
                    clearTimeout(timer);
                    timer = setTimeout(function () {
                        fn.apply(_this, args);
                        isFirst = true;
                    }, delay);
                };
            }
        </script>
    </body>
</html>
